﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web;

namespace Blank.Extends
{
    public static class JavascriptExtends
    {
        /// <summary>
        /// new DateTime().getTime()
        /// </summary>
        /// <param name="site"></param>
        /// <returns></returns>
        public static string GetTime()
        {
            Int64 retval = 0;
            DateTime st = new DateTime(1970, 1, 1);
            TimeSpan t = (DateTime.Now.ToUniversalTime() - st);
            retval = (Int64)(t.TotalMilliseconds + 0.5);
            return retval.ToString();
        }
        /// <summary>
        /// 取URL中指定参数的值
        /// </summary>
        /// <param name="response"></param>
        /// <param name="paramName"></param>
        /// <returns></returns>
        public static string GetParam(this HttpWebResponse response, string paramName)
        {
            var paramValue = string.Empty;
            var isFound = false;
            string search = response.ResponseUri.Query;

            if (string.IsNullOrEmpty(search))
            {
                return paramValue;
            }

            if (search.IndexOf("?") == 0 && search.IndexOf("=") > 1)
            {
                string[] arrSource = search.Substring(1, search.Length - 1).Split('&');
                for (int i = 0; i < arrSource.Length && !isFound; i++)
                {
                    if (arrSource[i].IndexOf("=") > 0)
                    {
                        if (arrSource[i].Split('=')[0].ToLower() == paramName.ToLower())
                        {
                            paramValue = arrSource[i].Split('=')[1];
                            isFound = true;
                        }
                    }
                }
            }
            return paramValue;
        }
        /// <summary>
        /// 取指定KEY的Cookie值
        /// </summary>
        /// <param name="response"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetCookie(this HttpWebResponse response, string key)
        {
            var val = string.Empty;
            foreach (Cookie cookie in response.Cookies)
            {
                if (cookie.Name.Equals(key))
                {
                    val = cookie.Value;
                    break;
                }
            }
            return UnEscape(val);
        }
        /// <summary>
        /// String 对象编码以便它们能在所有计算机上可读，
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Escape(this string str)
        {
            if (str == null)
                return String.Empty;

            StringBuilder sb = new StringBuilder();
            int len = str.Length;

            for (int i = 0; i < len; i++)
            {
                char c = str[i];
                //everything other than the optionally escaped chars _must_ be escaped 
                if (Char.IsLetterOrDigit(c) || c == '-' || c == '_' || c == '/' || c == '\\' || c == '.')
                    sb.Append(c);
                else
                    sb.Append(Uri.HexEscape(c));
            }

            return sb.ToString();
        }
        /// <summary>
        /// 这两个函数的功能是用来将字符进行编码我反编码（解码），
        /// 其主要用途在使用cookie时经常用到这两个函数，因为在要对cookie进行写入时，
        /// 那些特殊字符（符号和汉字）需要进行编码才能写入，所以在读取时就需要用到unescape函数进行解码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string UnEscape(this string str)
        {
            if (str == null)
                return String.Empty;

            StringBuilder sb = new StringBuilder();
            int len = str.Length;
            int i = 0;
            while (i != len)
            {
                if (Uri.IsHexEncoding(str, i))
                    sb.Append(Uri.HexUnescape(str, ref i));
                else
                    sb.Append(str[i++]);
            }
            return sb.ToString();
        }
    }
}
